<template>
    <el-form :model="form" ref="formRef">
        <el-form-item label="用户名:" prop="username" :rules="[{required:true,message:'请输入用户名'}]">
            <el-input v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="密码:" prop="password" :rules="[{required:true,message:'请输入密码'}]">
            <el-input v-model="form.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="角色:" prop="role" :rules="[{required:true,message:'请选择角色'}]">
            <el-radio-group v-model="form.role">
                <el-radio value="student">学生</el-radio>
                <el-radio value="teacher">教师</el-radio>
                <el-radio value="admin">管理员</el-radio>
            </el-radio-group>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="onSubmit">登录</el-button>
            <el-button @click="cancel">取消</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { useMemberStore } from '../stores/member'
import { ElMessage } from 'element-plus';

const form = ref({
    username:'',
    password:'',
    role:''
})
const formRef = ref(null)

const router = useRouter()
const userStore = useUserStore()
const memberStore = useMemberStore()

const onSubmit = () =>{
    formRef.value.validate((valid) => {
        if(valid){
            if(form.value.role === 'student' || form.value.role === 'teacher'){
                const user = memberStore.getUserByUsername(form.value.username)
                if(user && user.password === form.value.password && user.role === form.value.role){
                    userStore.login({username:user.username, role:user.role, name:user.name})
                    router.push(user.role === 'student' ? '/profile' : `/teacher/profile/${user.id}`)
                }else{
                    ElMessage.error('用户名或密码错误')
                    form.value.username = ''
                    form.value.password = ''
                }
            }else if(form.value.role === 'admin'){
                const admin = memberStore.getUserByUsername('admin')
                if(admin && form.value.password === admin.password){
                    userStore.login({username:admin.username,role:'admin',name:admin.name})
                    router.push('/admin')
                }else{
                    ElMessage.error('用户名或密码错误')
                    form.value.username = ''
                    form.value.password = ''
                }
            }
        }
    })
}

const cancel = () => {
    router.push('/')
}
</script>